package com.ics.cmsadmin.modules.wechat.controller;


import com.ics.cmsadmin.modules.wechat.base.controller.BaseController;
import com.ics.cmsadmin.modules.wechat.constanst.MsgConstant;
import com.ics.cmsadmin.modules.wechat.model.media.UploadMediasResult;
import com.ics.cmsadmin.modules.wechat.model.media.UploadNewsMedia;
import com.ics.cmsadmin.modules.wechat.model.req.BasicMsg;
import com.ics.cmsadmin.modules.wechat.model.resp.MassMsgResult;
import com.ics.cmsadmin.modules.wechat.model.resp.RespAbstractMsg;
import com.ics.cmsadmin.modules.wechat.model.resp.RespNewsMsg;
import com.ics.cmsadmin.modules.wechat.model.template.req.WechatTemplateMsg;
import com.ics.cmsadmin.modules.wechat.model.template.resp.TemplateMsgResult;
import com.ics.cmsadmin.modules.wechat.result.WechatResult;
import com.ics.cmsadmin.modules.wechat.service.WechatAuthService;
import com.ics.cmsadmin.modules.wechat.service.WechatMsgService;
import com.ics.cmsadmin.modules.wechat.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author phil
 * @date 2017年9月19日
 *
 */
@RestController
@RequestMapping("/api/wechat")
public class WechatMsgController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private WechatMsgService wechatMsgService;

    @Autowired
    private WechatAuthService wechatAuthService;

	/**
	 * 校验信息是否是从微信服务器发出，处理消息
	 *
	 * @param request
	 * @param out
	 * @throws IOException
	 */
	@RequestMapping(value = "/handler", method = { RequestMethod.GET, RequestMethod.POST })
	public String processPost(HttpServletRequest request) throws Exception {
		this.getRequest().setCharacterEncoding("UTF-8");
		this.getResponse().setCharacterEncoding("UTF-8");
		boolean ispost = Objects.equals("POST", this.getRequest().getMethod().toUpperCase());
		if (ispost) {
			logger.debug("接入成功，正在处理逻辑");
			String respXml = defaultMsgDisPose(request.getInputStream());// processRequest(request, response);
            logger.info("respXml = {}" , respXml);
			if (StringUtils.isNotBlank(respXml)) {
				return respXml;
			}
		} else {
			String signature = request.getParameter("signature");
			// 时间戳
			String timestamp = request.getParameter("timestamp");
			// 随机数
			String nonce = request.getParameter("nonce");
			// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
			if (SignatureUtil.checkSignature(signature, timestamp, nonce)) {
				// 随机字符串
				String echostr = this.getRequest().getParameter("echostr");
				logger.debug("接入成功，echostr {}", echostr);
				return echostr;
			}
		}
		return "";
	}

	/**
	 * 默认处理方法
	 *
	 * @param input
	 * @return
	 * @throws Exception
	 * @throws DocumentException
	 */
	private String defaultMsgDisPose(InputStream inputStream) throws Exception {
		String result = null;
		if (inputStream != null) {
			Map<String, String> params = XmlUtil.parseStreamToMap(inputStream);
			logger.info("input params = {}", params);
			if (params != null && params.size() > 0) {
				BasicMsg msgInfo = new BasicMsg();
				String createTime = params.get("CreateTime");
				String msgId = params.get("MsgId");
				msgInfo.setCreateTime(
						(createTime != null && !"".equals(createTime)) ? Integer.parseInt(createTime) : 0);
				msgInfo.setFromUserName(params.get("FromUserName"));
				msgInfo.setMsgId((msgId != null && !"".equals(msgId)) ? Long.parseLong(msgId) : 0);
				msgInfo.setToUserName(params.get("ToUserName"));
				WechatResult resultObj = coreHandler(msgInfo, params);
				if (resultObj == null) { //
					return null;
				}
				boolean success = resultObj.isSuccess(); // 如果 为true,则表示返回xml文件, 直接转换即可,否则按类型
				if (success) {
					result = resultObj.getObject().toString();
				} else {
					int type = resultObj.getType(); // 这里规定 1 图文消息 否则直接转换
					if (type == WechatResult.NEWSMSG) {
						RespNewsMsg newsMsg = (RespNewsMsg) resultObj.getObject();
						result = MsgUtil.newsMsgToXml(newsMsg);
					} else {
						RespAbstractMsg basicMsg = (RespAbstractMsg) resultObj.getObject();
						result = MsgUtil.msgToXml(basicMsg);
					}
				}
			} else {
				result = "msg is wrong";
			}
		}
		return result;
	}

	/**
	 * 核心处理
	 *
	 * @param msg
	 *            消息基类
	 * @param params
	 *            xml 解析出来的 数据
	 * @return
	 */
	private WechatResult coreHandler(BasicMsg msg, Map<String, String> params) {
		WechatResult result = null;
		String msgType = params.get("MsgType");
		if (StringUtils.isNotEmpty(msgType)) {
			switch (msgType) {
			case MsgConstant.REQ_MESSAGE_TYPE_TEXT: // 文本消息
				result = wechatMsgService.textMsg(msg, params);
				break;
			case MsgConstant.REQ_MESSAGE_TYPE_IMAGE: // 图片消息
				result = wechatMsgService.imageMsg(msg, params);
				break;
			case MsgConstant.REQ_MESSAGE_TYPE_LINK: // 链接消息
				result = wechatMsgService.linkMsg(msg, params);
				break;
			case MsgConstant.REQ_MESSAGE_TYPE_LOCATION: // 地理位置
				result = wechatMsgService.locationMsg(msg, params);
				break;
			case MsgConstant.REQ_MESSAGE_TYPE_VOICE: // 音频消息
				result = wechatMsgService.voiceMsg(msg, params);
				break;
			case MsgConstant.REQ_MESSAGE_TYPE_SHORTVIDEO: // 短视频消息
				result = wechatMsgService.shortvideo(msg, params);
				break;
			case MsgConstant.REQ_MESSAGE_TYPE_VIDEO: // 视频消息
				result = wechatMsgService.videoMsg(msg, params);
				break;
			case MsgConstant.REQ_MESSAGE_TYPE_EVENT: // 事件消息
				String eventType = params.get("Event"); //
				if (eventType != null && !"".equals(eventType)) {
					switch (eventType) {
					case MsgConstant.EVENT_TYPE_SUBSCRIBE:
						result = wechatMsgService.subscribe(msg, params);
						break;
					case MsgConstant.EVENT_TYPE_UNSUBSCRIBE:
						result = wechatMsgService.unsubscribe(msg, params);
						break;
					case MsgConstant.EVENT_TYPE_SCAN:
						result = wechatMsgService.scan(msg, params);
						break;
					case MsgConstant.EVENT_TYPE_LOCATION:
						result = wechatMsgService.eventLocation(msg, params);
						break;
					case MsgConstant.EVENT_TYPE_CLICK:
						result = wechatMsgService.eventClick(msg, params);
						break;
					case MsgConstant.EVENT_TYPE_VIEW:
						result = wechatMsgService.eventView(msg, params);
						break;
					case MsgConstant.KF_CREATE_SESSION:
						result = wechatMsgService.kfCreateSession(msg, params);
						break;
					case MsgConstant.KF_CLOSE_SESSION:
						result = wechatMsgService.kfCloseSession(msg, params);
						break;
					case MsgConstant.KF_SWITCH_SESSION:
						result = wechatMsgService.kfSwitchSession(msg, params);
						break;
					default:
						wechatMsgService.eventDefaultReply(msg, params);
						break;
					}
				}
				break;
			default:
				wechatMsgService.defaultMsg(msg, params);
			}
		}
		return result;
	}

	/**
	 * 仅仅是个示例
	 *
	 * @return
	 */
	@GetMapping("/sendTemplate")
	public TemplateMsgResult sendTemplate() {
        logger.info("templateMsgResult");
		TemplateMsgResult templateMsgResult = null;
		TreeMap<String, TreeMap<String, String>> params = new TreeMap<>();
		// 根据具体模板参数组装
		params.put("first", WechatTemplateMsg.item("您的户外旅行活动订单已经支付完成，可在我的个人中心中查看", "#000000"));
		params.put("keyword1", WechatTemplateMsg.item("8.1发现尼泊尔—人文与自然的旅行圣地", "#000000"));
		params.put("keyword2", WechatTemplateMsg.item("5000元", "#000000"));
		params.put("keyword3", WechatTemplateMsg.item("2017.1.2", "#000000"));
		params.put("keyword4", WechatTemplateMsg.item("5", "#000000"));
		params.put("remark", WechatTemplateMsg.item("请届时携带好身份证件准时到达集合地点，若临时退改将产生相应损失，敬请谅解,谢谢！", "#000000"));
		WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
		wechatTemplateMsg.setTemplate_id("YRNNLX6dXLYJouT6zp6081hi2A5l4t93Ka41TZ9V3ls");
		wechatTemplateMsg.setTouser("oh_DW1d2FSQJAKGQEfwaU4F_XosI");
		wechatTemplateMsg.setUrl("http://music.163.com/#/song?id=27867140");
		wechatTemplateMsg.setData(params);
		String data = JsonUtil.toJsonString(wechatTemplateMsg);
		templateMsgResult = wechatMsgService.sendTemplate(wechatAuthService.getAccessToken(), data);
		logger.info("templateMsgResult = {}", templateMsgResult);
		return templateMsgResult;
	}


	@RequestMapping("/mediaUploadimg")
	public String mediaUploadimg() throws Exception {
		// String mediaPath =
		// "http://localhost:8080/HiPhil_Phase1/img/534a75fe0af80021.jpg";
		String mediaPath = "/Users/yuan/Desktop/lake.jpg";
		// UploadMediasResult umr = HttpReqUtil.uploadTempMedia("phil_token", "image",
		// mediaPath);
		UploadMediasResult umr = HttpReqUtil.uploadTempMediaFile(wechatAuthService.getAccessToken(), "image", mediaPath, null);
		logger.debug(" mediaUploadimg result {} ", umr);
        return "";
	}

	@RequestMapping("/sendByOpenid")
	public MassMsgResult sendByOpenid() throws Exception {
		// 根据OpenID列表群发图文消息
		String mediaPath1 = "https://raw.githubusercontent.com/flutter/website/master/src/_includes/code/layout/lakes/images/lake.jpg";
        UploadMediasResult result1 = HttpReqUtil.uploadTempMedia(wechatAuthService.getAccessToken(), "image", mediaPath1, null);
        logger.info("result1 = {}", result1);
		String mediaPath2 = "https://raw.githubusercontent.com/flutter/website/master/src/_includes/code/layout/lakes/images/lake.jpg";
        UploadMediasResult result2 = HttpReqUtil.uploadTempMedia(wechatAuthService.getAccessToken(), "image", mediaPath2, null);
        logger.info("result2 = {}", result2);
		List<UploadNewsMedia> array = new ArrayList<>();
		UploadNewsMedia entity1 = new UploadNewsMedia();
		entity1.setAuthor("yuan");
		entity1.setContent("人生只有经历才会懂得,只有懂得才知道珍惜，一生中，总会有一个人让你笑得最甜，也总会有一个人让你痛得最深，忘记,是善待自己");
		entity1.setContent_source_url("http://blog.csdn.net/phil_jing");
		// entity1.setDigest("digest");
		entity1.setShow_conver_pic(1);
		entity1.setThumb_media_id(result1.getMedia_id());
		entity1.setTitle("心灵鸡汤");
		array.add(entity1);
		UploadNewsMedia entity2 = new UploadNewsMedia();
		entity2.setAuthor("yuan");
		entity2.setContent("什么是幸福，幸福就是自己的一种愉快的心理状态和感受。时时、事事都能使自己快乐的人才是最幸福的人。最快乐的人，就是最幸福的人。笑口常开的人，是最幸福的。");
		entity2.setContent_source_url("http://blog.csdn.net/phil_jing");
		// entity2.setDigest("digest");
		entity2.setShow_conver_pic(0);
		entity2.setThumb_media_id(result2.getMedia_id());
		entity2.setTitle(" 经典语录");
		array.add(entity2);
		// 获取图文消息结果
		UploadMediasResult ur = HttpReqUtil.uploadTempNewsMedia(wechatAuthService.getAccessToken(), array, null);
		logger.info("UploadMediasResult = {}", ur);
		List<String> openids = new ArrayList<>();
		openids.add("oh_DW1d2FSQJAKGQEfwaU4F_XosI");
//		openids.add("oh_DW1T2YemrYtnhgEfMlaKQwBWU");

		MassMsgResult result_news = wechatMsgService.previewMessage(wechatAuthService.getAccessToken(), "oh_DW1d2FSQJAKGQEfwaU4F_XosI", ur.getMedia_id());
		// MassMsgResult result_news = wechatMsgService.sendMpnewsToOpenid(wechatAuthService.getAccessToken(), openids, ur.getMedia_id());
		logger.debug(" send by openid msg {} ", result_news.getErrmsg());
//		// 根据OpenID列表群发文字消息
//		MassMsgResult result_text = wechatMsgService.sendTextToOpenid(wechatAuthService.getAccessToken(), openids,
//				"什么是幸福，幸福就是自己的一种愉快的心理状态和感受。时时、事事都能使自己快乐的人才是最幸福的人。最快乐的人，就是最幸福的人。笑口常开的人，是最幸福的");
//		logger.debug(" send by openid msg {} ", result_text.getErrmsg());
		return result_news;
	}

}
